package de.tapps.brainstorming;

import java.io.IOException;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.content.Context;
import android.os.AsyncTask;
import android.telephony.TelephonyManager;
import android.util.Log;
/**
 * Adds the mail of the user
 * @author Timo
 * Encrypted - ok
 */
public class AddMail extends AsyncTask<String, Integer, String> {
	String mail;
	private MainActivity activity = new MainActivity();
	private Crypter crypter;
	public AddMail(MainActivity act,String pmail){
		mail = pmail;
		activity = act;
		crypter = new Crypter(activity);

	}
	@Override
	protected String doInBackground(String... arg0) {
		new Thread(new Runnable() {
			public void run() {
				// Create a new HttpClient and Post Header
				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(
						"http://t-apps-online.de/BrainStorming/addMail.php");
				try {
					  SecureRandom random = new SecureRandom();

					String key = new BigInteger(130, random).toString(32);
					TelephonyManager telephonyManager = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
					String imei = telephonyManager.getDeviceId();
					Log.d("imei","Imei"+imei);
				     // Decode the bytes into a String
					List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
							1);
					nameValuePairs.add(new BasicNameValuePair("imei",
							""+crypter.encrypt(imei)));
					nameValuePairs.add(new BasicNameValuePair("mail",
							""+mail));
					nameValuePairs.add(new BasicNameValuePair("key",
							""+key));
					httppost.setEntity(new UrlEncodedFormEntity(
							nameValuePairs));
					// Execute HTTP Post Request
					HttpResponse response = httpclient.execute(httppost);
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
				} catch (IOException e) {
					// TODO Auto-generated catch block
				}
			}
		}).start();
		return null;
	}
}